<template>
  <div class="document-preview-page">
    <!-- 预览头部工具栏 -->
    <div class="preview-header">
      <div class="header-left">
        <el-button @click="goBack" class="back-btn">
          <el-icon><ArrowLeft /></el-icon>
          返回搜索
        </el-button>
        
        <div class="document-info">
          <h2 class="doc-title">{{ document.name }}</h2>
          <div class="doc-meta">
            <span class="doc-type">{{ document.type?.toUpperCase() }}</span>
            <span class="doc-size">{{ formatFileSize(document.size) }}</span>
            <span class="doc-date">{{ formatDate(document.updatedAt) }}</span>
          </div>
        </div>
      </div>
      
      <div class="header-actions">
        <el-button @click="zoomOut" :disabled="zoomLevel <= 50">
          <el-icon><ZoomOut /></el-icon>
        </el-button>
        <span class="zoom-level">{{ zoomLevel }}%</span>
        <el-button @click="zoomIn" :disabled="zoomLevel >= 200">
          <el-icon><ZoomIn /></el-icon>
        </el-button>
        
        <el-divider direction="vertical" />
        
        <el-button @click="toggleFullscreen" :type="isFullscreen ? 'primary' : 'default'">
          <el-icon><FullScreen /></el-icon>
          {{ isFullscreen ? '退出全屏' : '全屏' }}
        </el-button>
        
        <el-button @click="downloadDocument" type="primary">
          <el-icon><Download /></el-icon>
          下载
        </el-button>
        
        <el-button @click="toggleFavorite" :type="document.isFavorite ? 'warning' : 'default'">
          <el-icon><Star /></el-icon>
          {{ document.isFavorite ? '已收藏' : '收藏' }}
        </el-button>
        
        <el-dropdown @command="handleAction">
          <el-button>
            <el-icon><More /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="share">
                <el-icon><Share /></el-icon>
                分享链接
              </el-dropdown-item>
              <el-dropdown-item command="copy">
                <el-icon><DocumentCopy /></el-icon>
                复制链接
              </el-dropdown-item>
              <el-dropdown-item command="print">
                <el-icon><Printer /></el-icon>
                打印
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 主预览区域 -->
    <div class="preview-content" :class="{ fullscreen: isFullscreen }">
      <div class="preview-main">
        <!-- PDF预览 -->
        <div v-if="document.type === 'pdf'" class="pdf-viewer">
          <div class="pdf-controls">
            <el-button-group>
              <el-button @click="prevPage" :disabled="currentPage <= 1" size="small">
                <el-icon><ArrowLeft /></el-icon>
                上一页
              </el-button>
              <el-button @click="nextPage" :disabled="currentPage >= totalPages" size="small">
                下一页
                <el-icon><ArrowRight /></el-icon>
              </el-button>
            </el-button-group>
            
            <span class="page-info">
              第 {{ currentPage }} 页，共 {{ totalPages }} 页
            </span>
          </div>
          
          <div class="pdf-container" :style="{ transform: `scale(${zoomLevel / 100})` }">
            <!-- 这里应该集成 PDF.js 或其他 PDF 预览组件 -->
            <div class="pdf-placeholder">
              <el-icon size="64"><Document /></el-icon>
              <h3>{{ document.name }}</h3>
              <p>PDF 文档预览</p>
              <p class="placeholder-text">
                实际项目中这里会使用 PDF.js 来渲染真实的 PDF 内容
              </p>
            </div>
          </div>
        </div>
        
        <!-- Office文档预览 -->
        <div v-else-if="['docx', 'pptx', 'xlsx'].includes(document.type)" class="office-viewer">
          <div class="office-container" :style="{ transform: `scale(${zoomLevel / 100})` }">
            <div class="office-placeholder">
              <el-icon size="64"><Document /></el-icon>
              <h3>{{ document.name }}</h3>
              <p>{{ getDocumentTypeName(document.type) }} 文档预览</p>
              <p class="placeholder-text">
                实际项目中这里会集成 Office Online 或将文档转换为可预览格式
              </p>
              <div class="document-content">
                <h4>文档内容概要：</h4>
                <ul>
                  <li v-if="document.type === 'docx'">包含文本内容、表格、图像等元素</li>
                  <li v-if="document.type === 'pptx'">包含多张幻灯片，支持翻页浏览</li>
                  <li v-if="document.type === 'xlsx'">包含多个工作表，支持数据查看</li>
                  <li>支持搜索、复制、打印等操作</li>
                  <li>保持原文档格式和布局</li>
                </ul>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 图片预览 -->
        <div v-else-if="['jpg', 'png', 'gif', 'bmp', 'webp'].includes(document.type)" class="image-viewer">
          <div class="image-container" :style="{ transform: `scale(${zoomLevel / 100})` }">
            <img v-if="document.thumbnail" :src="document.thumbnail" :alt="document.name" />
            <div v-else class="image-placeholder">
              <el-icon size="64"><Picture /></el-icon>
              <h3>{{ document.name }}</h3>
              <p>图片文件预览</p>
            </div>
          </div>
        </div>
        
        <!-- 其他文件类型 -->
        <div v-else class="unsupported-viewer">
          <div class="unsupported-content">
            <el-icon size="64"><Warning /></el-icon>
            <h3>暂不支持预览此文件类型</h3>
            <p>文件名：{{ document.name }}</p>
            <p>文件类型：{{ document.type?.toUpperCase() }}</p>
            <p>建议下载到本地使用相应软件打开</p>
            <el-button @click="downloadDocument" type="primary" size="large">
              <el-icon><Download /></el-icon>
              下载文件
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 右侧信息面板 -->
      <div class="preview-sidebar" v-if="!isFullscreen">
        <!-- 文档信息 -->
        <div class="info-section">
          <h3>文档信息</h3>
          <div class="info-list">
            <div class="info-item">
              <label>文件名：</label>
              <span>{{ document.name }}</span>
            </div>
            <div class="info-item">
              <label>文件类型：</label>
              <span>{{ document.type?.toUpperCase() }}</span>
            </div>
            <div class="info-item">
              <label>文件大小：</label>
              <span>{{ formatFileSize(document.size) }}</span>
            </div>
            <div class="info-item">
              <label>创建时间：</label>
              <span>{{ formatDate(document.createdAt) }}</span>
            </div>
            <div class="info-item">
              <label>修改时间：</label>
              <span>{{ formatDate(document.updatedAt) }}</span>
            </div>
            <div class="info-item">
              <label>标签：</label>
              <div class="tags-container">
                <el-tag
                  v-for="tag in document.tags"
                  :key="tag"
                  size="small"
                  style="margin: 2px;"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 相关文档推荐 -->
        <div class="related-section">
          <h3>相关文档</h3>
          <div class="related-list">
            <div
              v-for="relatedDoc in relatedDocuments"
              :key="relatedDoc.id"
              class="related-item"
              @click="previewDocument(relatedDoc)"
            >
              <div class="related-icon">
                <el-icon><component :is="getDocumentIcon(relatedDoc.type)" /></el-icon>
              </div>
              <div class="related-info">
                <div class="related-name">{{ relatedDoc.name }}</div>
                <div class="related-meta">
                  <span>{{ relatedDoc.type?.toUpperCase() }}</span>
                  <span>{{ formatFileSize(relatedDoc.size) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 最近访问 -->
        <div class="recent-section">
          <h3>最近访问</h3>
          <div class="recent-list">
            <div
              v-for="recentDoc in recentDocuments"
              :key="recentDoc.id"
              class="recent-item"
              @click="previewDocument(recentDoc)"
            >
              <div class="recent-icon">
                <el-icon><component :is="getDocumentIcon(recentDoc.type)" /></el-icon>
              </div>
              <div class="recent-info">
                <div class="recent-name">{{ recentDoc.name }}</div>
                <div class="recent-time">{{ formatDate(recentDoc.lastAccessed) }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useDocumentStore } from '@/store/document'
import { ElMessage } from 'element-plus'
import {
  ArrowLeft, ZoomOut, ZoomIn, FullScreen, Download, Star, More,
  Share, DocumentCopy, Printer, Document, Picture, Warning,
  ArrowRight
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const documentStore = useDocumentStore()

// 响应式数据
const zoomLevel = ref(100)
const isFullscreen = ref(false)
const currentPage = ref(1)
const totalPages = ref(1)

// 获取文档数据
const document = reactive({
  id: '',
  name: '',
  type: '',
  size: 0,
  createdAt: '',
  updatedAt: '',
  tags: [],
  isFavorite: false,
  thumbnail: ''
})

// 相关文档和最近访问文档
const relatedDocuments = ref([])
const recentDocuments = ref([])

// 计算属性
const getDocumentTypeName = (type) => {
  const typeMap = {
    docx: 'Word',
    pptx: 'PowerPoint', 
    xlsx: 'Excel',
    pdf: 'PDF'
  }
  return typeMap[type] || type.toUpperCase()
}

const getDocumentIcon = (type) => {
  const iconMap = {
    pdf: 'Document',
    docx: 'Document',
    pptx: 'Document', 
    xlsx: 'Document',
    jpg: 'Picture',
    png: 'Picture',
    gif: 'Picture'
  }
  return iconMap[type] || 'Document'
}

// 方法
const goBack = () => {
  router.back()
}

const zoomIn = () => {
  if (zoomLevel.value < 200) {
    zoomLevel.value += 25
  }
}

const zoomOut = () => {
  if (zoomLevel.value > 50) {
    zoomLevel.value -= 25
  }
}

const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value
  
  if (isFullscreen.value) {
    document.documentElement.requestFullscreen?.()
  } else {
    document.exitFullscreen?.()
  }
}

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
  }
}

const downloadDocument = () => {
  ElMessage.success(`开始下载: ${document.name}`)
}

const toggleFavorite = () => {
  document.isFavorite = !document.isFavorite
  ElMessage.success(document.isFavorite ? '已添加到收藏' : '已取消收藏')
}

const handleAction = (command) => {
  switch (command) {
    case 'share':
      ElMessage.success('分享链接已生成')
      break
    case 'copy':
      ElMessage.success('链接已复制到剪贴板')
      break
    case 'print':
      window.print()
      break
  }
}

const previewDocument = (doc) => {
  router.push(`/preview/${doc.id}`)
}

const formatFileSize = (bytes) => {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const formatDate = (dateString) => {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return date.toLocaleDateString() + ' ' + date.toLocaleTimeString()
}

// 键盘快捷键
const handleKeyboard = (event) => {
  switch (event.key) {
    case 'Escape':
      if (isFullscreen.value) {
        toggleFullscreen()
      } else {
        goBack()
      }
      break
    case 'F11':
      event.preventDefault()
      toggleFullscreen()
      break
    case 'ArrowLeft':
      if (document.type === 'pdf') {
        prevPage()
      }
      break
    case 'ArrowRight':
      if (document.type === 'pdf') {
        nextPage()
      }
      break
    case '+':
    case '=':
      event.preventDefault()
      zoomIn()
      break
    case '-':
      event.preventDefault()
      zoomOut()
      break
  }
}

// 初始化数据
const initializeDocument = () => {
  const docId = route.params.id
  const foundDoc = documentStore.documents.find(d => d.id === docId)
  
  if (foundDoc) {
    Object.assign(document, foundDoc)
    
    // 设置PDF总页数（模拟数据）
    if (document.type === 'pdf') {
      totalPages.value = Math.floor(Math.random() * 20) + 5
    }
    
    // 加载相关文档
    relatedDocuments.value = documentStore.documents
      .filter(d => 
        d.id !== docId && 
        d.tags.some(tag => document.tags.includes(tag))
      )
      .slice(0, 5)
    
    // 加载最近访问文档
    recentDocuments.value = documentStore.documents
      .filter(d => d.id !== docId)
      .slice(0, 3)
      .map(d => ({
        ...d,
        lastAccessed: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000)
      }))
      
    // 记录访问历史
    documentStore.addToHistory(foundDoc)
  } else {
    ElMessage.error('文档不存在')
    goBack()
  }
}

onMounted(() => {
  initializeDocument()
  document.addEventListener('keydown', handleKeyboard)
  
  // 监听全屏变化
  document.addEventListener('fullscreenchange', () => {
    isFullscreen.value = !!document.fullscreenElement
  })
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeyboard)
})
</script>

<style lang="scss" scoped>
.document-preview-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--el-bg-color-page);
}

.preview-header {
  height: 60px;
  background: white;
  border-bottom: 1px solid var(--el-border-color-light);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  flex-shrink: 0;
  
  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;
    flex: 1;
    min-width: 0;
    
    .back-btn {
      .el-icon {
        margin-right: 4px;
      }
    }
    
    .document-info {
      min-width: 0;
      flex: 1;
      
      .doc-title {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
        color: var(--el-text-color-primary);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      
      .doc-meta {
        display: flex;
        gap: 12px;
        font-size: 12px;
        color: var(--el-text-color-secondary);
        margin-top: 2px;
        
        .doc-type {
          background: var(--el-color-primary-light-9);
          color: var(--el-color-primary);
          padding: 1px 6px;
          border-radius: 3px;
          font-weight: 500;
        }
      }
    }
  }
  
  .header-actions {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-shrink: 0;
    
    .zoom-level {
      min-width: 40px;
      text-align: center;
      font-size: 14px;
      color: var(--el-text-color-regular);
    }
  }
}

.preview-content {
  flex: 1;
  display: flex;
  overflow: hidden;
  
  &.fullscreen {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 9999;
    background: var(--el-bg-color);
  }
}

.preview-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: #f5f5f5;
}

.pdf-viewer {
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .pdf-controls {
    height: 50px;
    background: white;
    border-bottom: 1px solid var(--el-border-color-light);
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 20px;
    
    .page-info {
      font-size: 14px;
      color: var(--el-text-color-regular);
    }
  }
  
  .pdf-container {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: auto;
    padding: 20px;
    transform-origin: center;
    transition: transform 0.3s;
  }
}

.office-viewer,
.image-viewer {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: auto;
  padding: 20px;
  
  .office-container,
  .image-container {
    transform-origin: center;
    transition: transform 0.3s;
    
    img {
      max-width: 100%;
      max-height: 100%;
      box-shadow: 0 4px 20px rgba(0,0,0,0.1);
    }
  }
}

.pdf-placeholder,
.office-placeholder,
.image-placeholder {
  text-align: center;
  padding: 60px 40px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  max-width: 600px;
  
  .el-icon {
    color: var(--el-text-color-placeholder);
    margin-bottom: 16px;
  }
  
  h3 {
    margin: 0 0 8px 0;
    color: var(--el-text-color-primary);
  }
  
  p {
    margin: 0 0 16px 0;
    color: var(--el-text-color-secondary);
  }
  
  .placeholder-text {
    font-size: 12px;
    color: var(--el-text-color-placeholder);
    font-style: italic;
  }
  
  .document-content {
    margin-top: 24px;
    text-align: left;
    
    h4 {
      margin: 0 0 12px 0;
      color: var(--el-text-color-regular);
    }
    
    ul {
      margin: 0;
      padding-left: 20px;
      
      li {
        margin-bottom: 6px;
        color: var(--el-text-color-secondary);
        font-size: 14px;
      }
    }
  }
}

.unsupported-viewer {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .unsupported-content {
    text-align: center;
    padding: 60px 40px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.1);
    
    .el-icon {
      color: var(--el-color-warning);
      margin-bottom: 16px;
    }
    
    h3 {
      margin: 0 0 16px 0;
      color: var(--el-text-color-primary);
    }
    
    p {
      margin: 0 0 8px 0;
      color: var(--el-text-color-secondary);
      
      &:last-of-type {
        margin-bottom: 24px;
      }
    }
  }
}

.preview-sidebar {
  width: 300px;
  flex-shrink: 0;
  background: white;
  border-left: 1px solid var(--el-border-color-light);
  overflow-y: auto;
}

.info-section,
.related-section,
.recent-section {
  padding: 20px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  
  h3 {
    margin: 0 0 16px 0;
    font-size: 16px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
}

.info-list {
  .info-item {
    margin-bottom: 12px;
    
    label {
      display: block;
      font-size: 12px;
      color: var(--el-text-color-secondary);
      margin-bottom: 2px;
    }
    
    span {
      font-size: 14px;
      color: var(--el-text-color-primary);
      word-break: break-word;
    }
    
    .tags-container {
      display: flex;
      flex-wrap: wrap;
      gap: 4px;
    }
  }
}

.related-list,
.recent-list {
  .related-item,
  .recent-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 8px;
    border-radius: 6px;
    cursor: pointer;
    transition: background-color 0.2s;
    
    &:hover {
      background: var(--el-fill-color-light);
    }
    
    .related-icon,
    .recent-icon {
      width: 32px;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: var(--el-fill-color-lighter);
      border-radius: 4px;
      flex-shrink: 0;
      
      .el-icon {
        color: var(--el-text-color-secondary);
      }
    }
    
    .related-info,
    .recent-info {
      flex: 1;
      min-width: 0;
      
      .related-name,
      .recent-name {
        font-size: 13px;
        color: var(--el-text-color-primary);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        margin-bottom: 2px;
      }
      
      .related-meta {
        font-size: 11px;
        color: var(--el-text-color-placeholder);
        display: flex;
        gap: 8px;
      }
      
      .recent-time {
        font-size: 11px;
        color: var(--el-text-color-placeholder);
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .preview-content {
    flex-direction: column;
  }
  
  .preview-sidebar {
    width: 100%;
    height: 200px;
    border-left: none;
    border-top: 1px solid var(--el-border-color-light);
  }
  
  .header-left .document-info {
    .doc-title {
      font-size: 14px;
    }
  }
  
  .header-actions {
    .el-button span {
      display: none;
    }
  }
}
</style>